import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../../shared/smartadmin.config';
import "assets/js/bootstrap-switch.min.js";
import "assets/css/bootstrap-switch.min.css";

declare var $: any;
declare var Viewer: any;
@Component({
	selector: 'sa-jurisdiction-deploy',
	templateUrl: './jurisdiction-deploy.component.html',
	styleUrls:['./jurisdiction-deploy.component.css'],
})
export class JurisdictionDeployComponent implements OnInit {
	tableData:any = []; //table数据
	totalCount:number = 0; //分页总条数
	curPage:number = 1; //分页当前页
	pageSize:number = 10; //内置的分页每页条数
	formType:string = "add"; // 新增
  initDateRange: any = {
    startTime:'',
    endTime:'',
	}// 时间组件需要渲染的值
	tableParam:any = {
		companyId: '',
		companyName: '',
		name: '',
		dateType: '1',
		sortType: '1',
		status: '',
//	    startTime: '',
//	    endTime: '',
//	    searchKey: '',//搜索keyword
	}
	solutionConfigData: any = []; //弹窗表格数据
	isShowAdd: boolean = false;
	isShowDel: boolean = false;
	isShowEdit: boolean = false;

	constructor(private jsonApiService: JsonApiService, private router: Router,private activatedRoute: ActivatedRoute) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.curPage = queryParams.nowPage || 1;
		});
	}
	validatorOptions = {
		excluded:[":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			name: {
				validators: {
					notEmpty: {
						message: '请输入方案名称'
					}
				}
			},
			companyName: {
			  trigger:"change",
				validators: {
					notEmpty: {
						message: '请选择方案适用范围'
					}
				}
			},
		}
	}
	ngOnInit() {
		this.initBtn();
		this.initSwitch();
		System.import('assets/js/bootstrap-switch.min.js').then(
			()=>{System.import('assets/css/bootstrap-switch.min.css').then(()=>{
				this.load();
			})
		});
			// this.load();
	}
	//初始化权限按钮
	initBtn() {
		var btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_appletsManage:jurisdictionDeploy')));
		if(!btnData) {
			return
		};
		for(let item of btnData) {
			if(item.sourceKey === "jurisdictionDeploy:addBtn" && item.parentId) {
				this.isShowAdd = true;
			}
			if(item.sourceKey === "jurisdictionDeploy:delBtn" && item.parentId) {
				this.isShowDel = true;
			}
			if(item.sourceKey === "jurisdictionDeploy:editBtn" && item.parentId) {
				this.isShowEdit = true;
			}
		}
	}
	// 接收子组件传递过来的数据 
	getSelectTableTime(time){
		this.tableParam.startTime = time.startTime;
		this.tableParam.endTime = time.endTime;
	} 
	// 公司选中回调
  companySelected(data){
    this.tableParam.companyId = data.companyId;
    this.tableParam.companyName = data.companyName;
  }
	//表格搜索
	table_search() {
		this.curPage = 1
		this.tableParam.searchKey = common.stringTrim(this.tableParam.searchKey);
		this.load();
	}
	//刷新
	refresh(){
    	this.load();
    }
	//初始化加载list数据
	load() {
		var that = this;
		let data = {
			pageSize:this.pageSize,
			nowPage:this.curPage,
			parameters:{
				companyId: this.tableParam.companyId,
				name: this.tableParam.name.trim(),
				// dateType: this.tableParam.dateType,
				// sortType: this.tableParam.sortType,
				// status: this.tableParam.status,
//				startTime:this.tableParam.startTime,
//				endTime:this.tableParam.endTime,
//				searchKey:this.tableParam.searchKey,
			}
		}
		let reqdata = 'gridPager='+JSON.stringify(data);
		this.jsonApiService.http("appletResourceRole/list.html", reqdata).subscribe(data => {
			this.tableData = data.exhibitDatas;
			this.totalCount = data.recordCount;

			System.import("assets/js/bootstrap-switch.min.js").then(() => {
        System.import("assets/css/bootstrap-switch.min.css").then(() => {
          setTimeout(function () {
            that.initIsEnable();
          }, 1);
        });
      });
		})
	}
	// 删除
	delRow(row) {
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(() => {
			let reqdata = 'id=' + row.id;
			this.jsonApiService.http("appletResourceRole/delete.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				this.load();
			})
		})
	}
	//分页回调
	paginate(e){
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.load();
	}
	//初始化开关
  initIsEnable() {
    var that = this;
    $(".isEnable").bootstrapSwitch({
      //初始化按钮
      onText: "开启",
      offText: "停用",
      onColor: "primary",
      offColor: "warning",
      onSwitchChange: function (event, state) {
        if (state == true) {
          that.checkStatus("1", event.target.id);
        } else {
          that.checkStatus("0", event.target.id);
        }
      },
    });
  }
	//是否启用
  checkStatus(check, id) {
    this.jsonApiService.http_get(`appletResourceRole/updateStatus.html?id=${id}&status=${check}`).subscribe((data) => {
      if (data.success) {
        this.load();
      } else {
        this.jsonApiService.message(data.message);
      }
    });
  }
	/**
	 *   项目事件新增编辑模块===========================================================================================
	 */
	contractForm:any = {
		id: "",
		name: "",
		appletResourceCompanyList: [],
		resourceList: [],
		companyName: "",
		companyId: "",
		status: "1",
	}
	modelType:string = '1';
	addCompanySelected(data) {
    this.contractForm.companyId = data.companyIdSelectedList.join(',');
    this.contractForm.companyName = data.companyNameSelectedList.join(',');
  }
	initSwitch() {
		var that = this;
		$('.isStatus').bootstrapSwitch('destroy');  
		$('.isStatus').bootstrapSwitch({    //初始化按钮
				onText: "开启",
				offText: "关闭",
				onColor: "primary",
				offColor: "warning",
				onSwitchChange: function (event, state) {
						that.contractForm[event.target.name] = state? '1': '0';
				}
		});
	}
	
	// 添加项目事件界面打开
	showAddUserModal(modal){
	  modal.show();
	  $("#projectEventForm").data('bootstrapValidator').resetForm();
		this.formType = 'add'
		let that = this;
		this.contractForm = {
			id: "",
			name: "",
			appletResourceCompanyList: [],
			resourceList:[],
			companyName: "",
			companyId: "",
			status: "1",
		}
		setTimeout(()=>{
			that.initSwitch();
			that.AddUserLoad(1); // 传值1 说明是新增
		},10)
		$(".isStatus").bootstrapSwitch('state', true)
	}
	//初始化加载list数据  TODO
  AddUserLoad(type) {
		let that = this
    this.jsonApiService.http("appletResource/listAll.html",{}).subscribe((result) => {
			let dataList = JSON.parse(JSON.stringify(result.data)) || [];
			if(type == 2){
				for(let i=0;i< this.contractForm.resourceList.length;i++){
					for(let j=0;j<dataList.length;j++){
						if(this.contractForm.resourceList[i].id == dataList[j].id){
							dataList[j].isHide = this.contractForm.resourceList[i].isHide
						}
					}
				}
			}
      this.solutionConfigData = JSON.parse(JSON.stringify(dataList));

      System.import("assets/js/bootstrap-switch.min.js").then(() => {
        System.import("assets/css/bootstrap-switch.min.css").then(() => {
          setTimeout(function () {
            that.initHideSwitch();
          }, 1);
        });
      });
    });
  }

	initHideSwitch() {
		var that = this;
		$('.isHide').bootstrapSwitch('destroy');  
		$('.isHide').bootstrapSwitch({    //初始化按钮
				onText: "开启",
				offText: "关闭",
				onColor: "primary",
				offColor: "warning",
				onSwitchChange: function (event, state) {
					var id = event.target.id;
					for(let i =0;i <that.solutionConfigData.length;i++){
						if(that.solutionConfigData[i].id == id){
							that.solutionConfigData[i].isHide = state? '1': '0';
						}
					}
				}
		});
	}

	// 编辑项目事件
	editRow(row,modal,type){
		var that = this;
		modal.show();
		$("#projectEventForm").data('bootstrapValidator').resetForm();
		this.formType = type;
		row = JSON.parse(JSON.stringify(row));
		for(let key in this.contractForm){
			this.contractForm[key] = row[key];
		}
		let tenArr1:any = [],tenArr2:any = [];
		for(let item of row.appletResourceCompanyList){
				tenArr1.push(item.companyName);
				tenArr2.push(item.companyId);
		}
		this.contractForm.companyName = tenArr1.join(',');
		this.contractForm.companyId = tenArr2.join(',');

		setTimeout(()=>{
			that.initSwitch();
			//需要比对数据
			that.AddUserLoad(2); // 传值2 说明是编辑
		},10)
	}
	viewRow(row,modal,type){
	    modal.show();
			this.formType = type;
			row = JSON.parse(JSON.stringify(row));
			for(let key in this.contractForm){
					this.contractForm[key] = row[key];
			}
			let tenArr1:any = [],tenArr2:any = [];
			for(let item of this.contractForm.appletResourceCompanyList){
					tenArr1.push(item.companyName);
					tenArr2.push(item.companyId);
			}
			this.contractForm.companyName = tenArr1.join(',');
			this.contractForm.companyId = tenArr2.join(',');

	}
	closeProjectEventModal(modal) {
		modal.hide();
	}
	// 添加项目事件关闭
	closeSolutionConfigModal(modal){
		$("#projectEventForm").data('bootstrapValidator').resetForm();
		modal.hide();
	}
	// 提交
	solutionConfigSubmit(modal){
		$('#projectEventForm').bootstrapValidator('validate'); //开启验证
		let isValid = $('#projectEventForm').data('bootstrapValidator').isValid();  //验证是否通过
		if(isValid){
			let attr1 = this.contractForm.companyId.split(',');
			let attr2 = this.contractForm.companyName.split(',');
			let companyArray = []
			for(let i=0;i<attr1.length;i++){
				var companyArrayObj = {
					'companyId': attr1[i],
					'companyName':attr2[i]
				}
				companyArray.push(companyArrayObj)
			}
			let reqdata = {
					id: this.contractForm.id,
					name: this.contractForm.name,
					companyArray: JSON.stringify(companyArray),
					// companyId: this.contractForm.companyId,
					// companyId: this.contractForm.companyId,
					appletResourceArray: JSON.stringify(this.solutionConfigData),
					status: this.contractForm.status,
			}
			this.jsonApiService.http_obj('appletResourceRole/modify.html', reqdata).subscribe(data => {
				if(data.success){
						this.closeSolutionConfigModal(modal);
						this.load();
				}
				this.jsonApiService.message(data.message);
      })
		}
	}


	programme: any = ''; //详细范围
	//查看范围
	viewRange(row,modal) {
		let tenArr1:any = [];
		for(let item of row.appletResourceCompanyList){
				tenArr1.push(item.companyName);
		}
		this.programme = tenArr1.join(',');
		modal.show();
	}
	closeViewRangeModal(modal) {
		modal.hide();
	}
}